/*
 * @Autor: dingxiaolin
 * @Date: 2020-03-09 17:31:43
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-06-06 18:41:37
 */

import React, { Component } from "react";
import { Route, Switch, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import { adminRoutes } from "@/routes";
import { Frame } from "components";

const mapState = (state) => ({
  isLogin: state.user.isLogin,
  role: state.user.role,
});
@connect(mapState)
class App extends Component {
  renderComponent = (adminRoutes) => {
    return adminRoutes.map((route) => {
      return route.children
        ? this.renderComponent(route.children)
        : route.pathname && (
            <Route
              key={route.pathname}
              path={route.pathname}
              exact
              render={(routerProps) => {
                const hasPermission = route.roles.includes(this.props.role);
                return hasPermission ? (
                  <route.component {...routerProps} />
                ) : (
                  <Redirect to="/admin/noauth" />
                );
              }}
            />
          );
    });
  };
  render() {
    return this.props.isLogin ? (
      <Frame>
        <Switch>
          {this.renderComponent(adminRoutes)}
          <Redirect to={adminRoutes[0].pathname} from="/admin" exact />
          <Redirect to="/404" />
        </Switch>
      </Frame>
    ) : (
      <Redirect to="/login" />
    );
  }
}

export default App;
